package com.ytzl.itrip.biz.controller;

import com.ytzl.itrip.beans.model.*;
import com.ytzl.itrip.beans.model.vo.*;
import com.ytzl.itrip.biz.service.ItripCommentService;
import com.ytzl.itrip.biz.service.ItripHotelService;
import com.ytzl.itrip.biz.service.ItripImageService;
import com.ytzl.itrip.biz.service.ItripLabelDicService;
import com.ytzl.itrip.utils.common.*;
import org.apache.commons.io.FilenameUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

/**
 * Created by asus on 2018/7/24.
 */
@Controller
@RequestMapping("/api/comment")
public class SystemCommentController {

    @Resource
    private ValidationUtil validationUtil;
    @Resource
    private ItripCommentService itripCommentService;
    @Resource
    private ItripImageService itripImageService;
    @Resource
    private ItripHotelService itripHotelService;
    @Resource
    private ItripLabelDicService itripLabelDicService;

    @RequestMapping(value = "/getcommentlist",method = RequestMethod.POST)
    @ResponseBody
    public Dto getCommentlist(@RequestBody ItripSearchCommentVo itripSearchCommentVo){
        Map map = new HashMap();
        map.put("hotelId",itripSearchCommentVo.getHotelId());
        if (itripSearchCommentVo.getIsHavingImg()!=-1){
            map.put("isHavingImg",itripSearchCommentVo.getIsHavingImg());
        }
        if (itripSearchCommentVo.getIsOk()!=-1){
            map.put("isOk",itripSearchCommentVo.getIsOk());
        }
        try {
            Page page = itripCommentService.queryPageByMap(map,
                    itripSearchCommentVo.getPageNo(),
                    itripSearchCommentVo.getPageSize());
            return DtoUtil.returnDataSuccess(page);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评论列表错误","100020");
        }
    }

    @RequestMapping(value = "/getcount/{hotelId}",method = RequestMethod.GET)
    @ResponseBody
    public Dto getcount(@PathVariable String hotelId){
        if (hotelId!=null){
            Map map = new HashMap();
            map.put("hotelId",hotelId);
            ItripGetCountVo itripGetCountVo = new ItripGetCountVo();
            try {
                itripGetCountVo.setAllcomment(itripCommentService.getCountByMap(map));
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取酒店全部评论数失败","100014");
            }
            try {
                itripGetCountVo.setIsok(itripCommentService.getisok(map));
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取酒店值得推荐评论数失败","100017");
            }
            try {
                itripGetCountVo.setImprove(itripCommentService.getimprove(map));
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取酒店有待改善评论数失败","100016");
            }
            try {
                map.put("isOk",null);
                itripGetCountVo.setHavingimg(itripCommentService.getishavingimg(map));
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取酒店有图片评论数失败","100015");
            }
            return DtoUtil.returnSuccess("获取酒店各类评论数成功",itripGetCountVo);
        }else{
            return DtoUtil.returnFail("参数hotelId为空","100018");
        }
    }

    @RequestMapping(value = "/gethotelscore/{hotelId}",method = RequestMethod.GET)
    @ResponseBody
    public Dto gethotelscore(@PathVariable String hotelId){
        if (hotelId!=null){
            try {
                HotelScoreVo hotelScoreVo = itripCommentService.getHotelScore(hotelId);
                return DtoUtil.returnDataSuccess(hotelScoreVo);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取评分失败","100001");
            }
        }else{
            return DtoUtil.returnFail("hotelId不能为空","100002");
        }
    }

    @RequestMapping(value = "/getimg/{targetId}",method = RequestMethod.GET)
    @ResponseBody
    public Dto getimg(@PathVariable String targetId){
        if (targetId!=null && targetId!=""){
            Map map = new HashMap();
            map.put("type","2");
            map.put("targetId",targetId);
            List<ItripImageVo> itripImageVos = new ArrayList<>();
            try {
                List<ItripImage> itripImages = itripImageService.getListByMap(map);
                for (ItripImage itripImage:itripImages){
                    ItripImageVo itripImageVo = new ItripImageVo();
                    BeanUtils.copyProperties(itripImage,itripImageVo);
                    itripImageVos.add(itripImageVo);
                }
                return DtoUtil.returnSuccess("获取图片评论成功",itripImageVos);
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("获取评论图片失败","100012");
            }
        }else{
            return DtoUtil.returnFail("评论id不能为空","100013");
        }
    }

    @RequestMapping(value = "/gethoteldesc/{hotelId}",method = RequestMethod.GET)
    @ResponseBody
    public Dto gethoteldesc(@PathVariable String hotelId){
        try {
            ItripHotel itripHotel = itripHotelService.getById(Long.parseLong(hotelId));
            HotelDescVo hotelDescVo = new HotelDescVo();
            BeanUtils.copyProperties(itripHotel,hotelDescVo);
            return DtoUtil.returnDataSuccess(hotelDescVo);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取酒店相关信息错误","100021");
        }
    }

    @RequestMapping(value = "/gettraveltype",method = RequestMethod.GET)
    @ResponseBody
    public Dto gettraveltype(){
        Map map = new HashMap();
        map.put("parentId",107);
        List<TravelTypeVo> travelTypeVos = new ArrayList<>();
        try {
            List<ItripLabelDic> itripLabelDics = itripLabelDicService.getListByMap(map);
            for (ItripLabelDic itripLabelDic:itripLabelDics){
                TravelTypeVo travelTypeVo = new TravelTypeVo();
                BeanUtils.copyProperties(itripLabelDic,travelTypeVo);
                travelTypeVos.add(travelTypeVo);
            }
            return DtoUtil.returnSuccess("获取旅游类型列表成功",travelTypeVos);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取旅游类型列表错误","100019");
        }
    }

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public Dto upload(HttpServletRequest request,
                      HttpServletResponse response){
        ItripUser itripUser = validationUtil.getuser(request.getHeader("token"));
        if (null==itripUser){
            return DtoUtil.returnFail("token失效，请重新登录","100000");
        }
        //返回结果
        List<String> datalist = new ArrayList<>();
        CommonsMultipartResolver multipartResolver = new
                CommonsMultipartResolver(request.getSession().getServletContext());
        //判断当前request是否是Multiparty类型
        if (multipartResolver.isMultipart(request)){
            MultipartHttpServletRequest mhRequest =
                    (MultipartHttpServletRequest) request;
            //获取文件上传数量
            int fileCount = 0;
            try{
                fileCount=mhRequest.getFileMap().size();
            }catch (Exception e){
                e.printStackTrace();
                fileCount = 0;
                return DtoUtil.returnFail("文件大小超限","100009");
            }
            if (fileCount < 1 || fileCount > 4){
                return DtoUtil.returnFail("文件数目不正确，必须是大于1小于4"
                        ,"100007");
            }
            //获取所有文件上传名称
            Iterator<String> fileNames = mhRequest.getFileNames();
            while (fileNames.hasNext()){
                //获取文件
                MultipartFile file = mhRequest.getFile(fileNames.next());
                String fileName = file.getOriginalFilename();
                if (!fileName.trim().equals("") && (fileName.toLowerCase().contains("jpg")
                || fileName.toLowerCase().contains("png")
                || fileName.toLowerCase().contains("jpeg"))){
                    //创建新的文件名 userId-time-random.jpg
                    String newFileName = itripUser.getId()+"-"+System.currentTimeMillis()+"-"
                            +new Random().nextInt(1000000)+"."+
                            //获取原本文件的后缀名
                            FilenameUtils.getExtension(fileName);
                    String uploadPath = PropertiesUtils.get("public.properties","uploadPath");
                    File file1 = new File(uploadPath+File.separator+newFileName);
                    //如果父级不存在，创建
                    if (!file1.getParentFile().exists()){
                        file1.getParentFile().mkdirs();
                    }
                    //文件上传
                    try {
                        file.transferTo(file1);
                        String visitImgUrl = PropertiesUtils.get("public.properties","visitImgUrl");
                        datalist.add(visitImgUrl + newFileName);
                    } catch (IOException e) {
                        e.printStackTrace();
                        return DtoUtil.returnFail("文件上传失败","100006");
                    }
                }else {
                    return DtoUtil.returnFail("请求的内容不是上传文件的类型","100008");
                }
            }
        }
        return DtoUtil.returnDataSuccess(datalist);
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
    public Dto add(@RequestBody ItripAddCommentVo itripAddCommentVo,
                   HttpServletRequest request){
        ItripUser itripUser = validationUtil.getuser(request.getHeader("token"));
        if (null==itripUser){
            return DtoUtil.returnFail("token失效","100000");
        }
        if (itripAddCommentVo==null){
            return DtoUtil.returnFail("不能提交空，请填写评论信息","100004");
        }
        ItripComment itripComment = new ItripComment();
        BeanUtils.copyProperties(itripAddCommentVo,itripComment);
        itripComment.setUserId(itripUser.getId());
        if (itripAddCommentVo.getOrderId()==null){
            return DtoUtil.returnFail("订单id不能为空","100005");
        }
        try {
            itripComment.setUserId(itripUser.getId());
            itripCommentService.save(itripComment);
            for (int i=0;i<itripAddCommentVo.getItripImages().size();i++){
                ItripImage itripImage = new ItripImage();
                itripImage.setType("2");
                itripImage.setTargetId(Long.parseLong(String.valueOf(itripComment.getId())));
                itripImage.setImgUrl(itripAddCommentVo.getItripImages().get(i).getImgUrl());
                itripImage.setPosition(i+1);
                itripImage.setCreatedBy(itripUser.getId());
                itripImageService.save(itripImage);
            }
            return DtoUtil.returnSuccess("新增评论成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("新增评论失败","100003");
        }
    }

    @RequestMapping(value = "/delpic",method = RequestMethod.POST)
    @ResponseBody
    public Dto delpic(@Param("imgName") String imgName,
                      HttpServletRequest request){
        ItripUser itripUser = validationUtil.getuser(request.getHeader("token"));
        if (itripUser==null){
            return DtoUtil.returnFail("token失效","10000");
        }
        String uploadPath = PropertiesUtils.get("public.properties","uploadPath");
        File file = new File(uploadPath+File.separator+imgName);
        if (!file.exists()){
            return DtoUtil.returnFail("文件不存在，删除失败","100010");
        }
        try {
            file.delete();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("系统异常，删除失败","100009");
        }
        return DtoUtil.returnSuccess("删除成功");
    }

}
